<template>
  <div class="h-full">
    <loading-empty-wrapper :loading="loading" :empty="empty">
      <n-form
        :disabled="billStatus === 0"
        size="small"
        label-placement="left"
        label-width="100"
        :show-feedback="false"
        inline
      >
        <n-scrollbar x-scrollable>
          <n-space vertical :size="[4, 2]" class="min-w-1300px min-h-125px">
            <n-space :size="[4, 2]">
              <n-form-item label="单据日期" label-width="80" path="A_BILLDATE">
                <n-date-picker
                  v-model:formatted-value="formModel.A_BILLDATE"
                  :disabled="billStatus !== 0"
                  type="date"
                  value-format="yyyy/MM/dd"
                  format="yyyy/MM/dd"
                  class="w-120px"
                />
              </n-form-item>
              <n-form-item label="单据编号" path="A_BILLNO">
                <n-input v-model:value="formModel.A_BILLNO" size="tiny" disabled placeholder="" style="width: 150px" />
              </n-form-item>
              <n-form-item label="处理部门" label-width="80" path="A_DEPTID_DEPTNAME">
                <n-input
                  v-model:value="formModel.A_DEPTID_DEPTNAME"
                  size="tiny"
                  disabled
                  placeholder=""
                  style="width: 130px"
                />
              </n-form-item>
              <n-form-item label="供应商名称" path="A_OBJID_CUSTNAME">
                <n-input
                  v-model:value="formModel.A_OBJID_CUSTNAME"
                  size="tiny"
                  disabled
                  placeholder=""
                  style="width: 140px"
                />
              </n-form-item>
              <n-form-item label="移动电话" path="A_OBJID_MOBILETEL">
                <n-input
                  v-model:value="formModel.A_OBJID_MOBILETEL"
                  size="tiny"
                  disabled
                  placeholder=""
                  style="width: 110px"
                />
              </n-form-item>
              <n-form-item label="入库(单)" label-width="70" path="A_INCOUNT">
                <n-input v-model:value="formModel.A_INCOUNT" size="tiny" disabled placeholder="" style="width: 80px" />
              </n-form-item>
            </n-space>
            <n-space :size="[4, 2]">
              <n-form-item label="备注" label-width="80" path="A_REMARK">
                <n-input
                  v-model:value="formModel.A_REMARK"
                  :disabled="billStatus !== 0"
                  :placeholder="billStatus === 0 ? '请输入' : ' '"
                  size="tiny"
                  style="width: 832px"
                />
              </n-form-item>
              <n-form-item label="发票号码" path="A_INVOICENO">
                <n-input
                  v-model:value="formModel.A_INVOICENO"
                  size="tiny"
                  disabled
                  placeholder=""
                  style="width: 110px"
                />
              </n-form-item>
              <n-form-item label="退货(单)" label-width="70" path="A_OUTCOUNT">
                <n-input v-model:value="formModel.A_OUTCOUNT" size="tiny" disabled placeholder="" style="width: 80px" />
              </n-form-item>
            </n-space>
            <n-space :size="[4, 2]">
              <n-form-item label="供应商备注" label-width="80" path="A_SUPREMARK">
                <n-input
                  v-model:value="formModel.A_SUPREMARK"
                  size="tiny"
                  disabled
                  placeholder=""
                  style="width: 832px"
                />
              </n-form-item>
              <n-form-item label="处理状态" path="A_TJSTATUS">
                <n-select
                  v-model:value="formModel.A_TJSTATUS"
                  size="tiny"
                  :options="statusSelectOptions"
                  disabled
                  class="w-110px"
                />
              </n-form-item>
            </n-space>
            <n-space :size="[4, 2]">
              <n-form-item label="入库金额" label-width="80" path="A_AMOUNT">
                <n-input v-model:value="formModel.A_AMOUNT" size="tiny" disabled placeholder="" style="width: 120px" />
              </n-form-item>
              <n-form-item label="结算金额" path="A_JSAMOUNT">
                <n-input
                  v-model:value="formModel.A_JSAMOUNT"
                  size="tiny"
                  disabled
                  placeholder=""
                  style="width: 150px"
                />
              </n-form-item>
              <n-form-item label="差异金额" label-width="80" path="A_CYAMOUNT">
                <n-input
                  v-model:value="formModel.A_CYAMOUNT"
                  size="tiny"
                  disabled
                  placeholder=""
                  style="width: 130px"
                />
              </n-form-item>
              <n-form-item label="损耗扣款金额" path="A_JSKKAMOUNT1">
                <n-input
                  v-model:value="formModel.A_JSKKAMOUNT1"
                  size="tiny"
                  disabled
                  placeholder=""
                  style="width: 140px"
                />
              </n-form-item>
              <n-form-item label="促销扣款金额" path="A_JSKKAMOUNT2">
                <n-input
                  v-model:value="formModel.A_JSKKAMOUNT2"
                  size="tiny"
                  disabled
                  placeholder=""
                  style="width: 110px"
                />
              </n-form-item>
              <n-form-item label="调整金额" label-width="70" path="A_JSKKAMOUNT3">
                <n-input
                  v-model:value="formModel.A_JSKKAMOUNT3"
                  size="tiny"
                  disabled
                  placeholder=""
                  style="width: 80px"
                />
              </n-form-item>
            </n-space>
            <n-space :size="[4, 2]">
              <n-form-item label="应开票金额" label-width="80" path="A_KPAMOUNT">
                <n-input
                  v-model:value="formModel.A_KPAMOUNT"
                  size="tiny"
                  disabled
                  placeholder=""
                  style="width: 120px"
                />
              </n-form-item>
              <n-form-item label="其他扣款金额" path="A_KKAMOUNT">
                <n-input
                  v-model:value="formModel.A_KKAMOUNT"
                  size="tiny"
                  disabled
                  placeholder=""
                  style="width: 150px"
                />
              </n-form-item>
              <n-form-item label="应付金额" label-width="80" path="A_APAMOUNT">
                <n-input
                  v-model:value="formModel.A_APAMOUNT"
                  size="tiny"
                  disabled
                  placeholder=""
                  style="width: 130px"
                />
              </n-form-item>
              <n-form-item v-show="billStatus === 0">
                <n-button size="tiny" type="primary" ghost attr-type="button" @click="submitBill('0')">
                  <icon-bx:save class="mr-5px" />保存
                </n-button>
              </n-form-item>
              <n-form-item v-show="billStatus === 0">
                <n-button size="tiny" type="primary" ghost attr-type="button" @click="submitBill('1')">
                  <icon-mdi:page-next-outline class="mr-5px" />提交
                </n-button>
              </n-form-item>
              <n-form-item v-show="billStatus === 0">
                <n-button size="tiny" @click="refreshBillPrice"><icon-mdi:reload class="mr-5px" />刷新结算价</n-button>
              </n-form-item>
            </n-space>
          </n-space>
        </n-scrollbar>
      </n-form>
    </loading-empty-wrapper>
    <ul class="info-data">
      <li v-for="(item, index) in infoData" :key="index">
        <span>{{ item[0] }}:</span>
        <span>{{ item[1] || '-' }}</span>
      </li>
    </ul>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watch, onMounted, onUnmounted } from 'vue';
import { useDateFormat } from '@vueuse/core';
import { fetchPurchaseDetail, fetchSubmitBill, fetchRefreshPrice } from '@/service';
import { useAppStore } from '@/store';
import { useBillContext } from '@/context';
import { useLoadingEmpty } from '@/hooks';

const { useInject } = useBillContext();
const { billNo, billStatus, billDatas, setBillDatas, setRefreshBill } = useInject();

// 初始加载
const { loading, startLoading, endLoading, empty } = useLoadingEmpty();

// 初始状态选择项
const statusSelectOptions = [
  {
    label: '未提交',
    value: '0'
  },
  {
    label: '已提交',
    value: '1'
  },
  {
    label: '已退回',
    value: '2'
  },
  {
    label: '受理通过',
    value: '3'
  }
];

// 初始表单
function createDefaultFormModel(): any {
  return {
    A_BILLDATE: null,
    A_BILLNO: null,
    A_DEPTID_DEPTNAME: null,
    A_OBJID_CUSTNAME: null,
    A_OBJID_MOBILETEL: null,
    A_INCOUNT: null,
    A_REMARK: null,
    A_INVOICENO: null,
    A_OUTCOUNT: null,
    A_SUPREMARK: null,
    A_TJSTATUS: null,
    A_AMOUNT: null,
    A_JSAMOUNT: null,
    A_CYAMOUNT: null,
    A_JSKKAMOUNT1: null,
    A_JSKKAMOUNT2: null,
    A_JSKKAMOUNT3: null,
    A_KPAMOUNT: null,
    A_KKAMOUNT: null,
    A_APAMOUNT: null
  };
}

// 处理接口数据
const formModel = reactive(createDefaultFormModel());
const infoData = ref<any>([]);
function setDataSource(data: any) {
  Object.assign(formModel, data);
  if (data.A_TJTIME) {
    infoData.value = [
      ['制单人', data.A_LISTERID_STAFFNAME],
      ['提交人', data.A_TJUSER_STAFFNAME],
      ['提交日期', data.A_TJTIME ? useDateFormat(data.A_TJTIME, 'YYYY/MM/DD').value : null],
      ['受理人', data.A_SLUSER_STAFFNAME],
      ['受理日期', data.A_SLTIME ? useDateFormat(data.A_SLTIME, 'YYYY/MM/DD').value : null],
      ['审核人', data.A_CONFIRMPERSIONID_STAFFNAME],
      ['审核日期', data.A_CONFIRMDATE ? useDateFormat(data.A_CONFIRMDATE, 'YYYY/MM/DD').value : null]
    ];
  }
}

// 获取接口数据并处理加载状态
async function getDataSource(n: any) {
  startLoading();
  const { data } = await fetchPurchaseDetail(n);
  if (data) {
    setDataSource(numToStr(data));
    endLoading();
  }
}

// 数字转字符型
function numToStr(data: any) {
  for (const x in data) {
    if (data[x] === '') {
      data[x] = null;
    } else if (typeof data[x] === 'number') {
      data[x] = String(data[x]);
    }
  }
  return data;
}

// 保存/提交对账单
async function submitBill(type: string) {
  setRefreshBill(false);
  const remark = formModel.A_REMARK !== null ? formModel.A_REMARK : '';
  const datas = { billDate: formModel.A_BILLDATE, billRemark: remark };
  const res: any = await fetchSubmitBill(type, billNo.value, datas);
  const app = useAppStore();
  if (res.data) {
    if (res.data.detail) setBillDatas(res.data.detail);
    if (res.data.deleteIds.length !== 0) setRefreshBill(true);
    // 保存
    if (type === '0') {
      window.$message?.success(`对账单保存成功`);
    } else {
      // 提交
      window.$message?.success(`对账单提交成功`);
      app.reloadPage();
    }
  } else {
    app.reloadPage();
  }
}

// 刷新结算价
async function refreshBillPrice() {
  setRefreshBill(false);
  const res: any = await fetchRefreshPrice(billNo.value);
  if (res.data) {
    setBillDatas(res.data);
    setRefreshBill(true);
    window.$message?.success(`刷新结算价成功！`);
  }
}

const updataDatas = watch(
  () => billDatas.value,
  newDatas => {
    setDataSource(numToStr(newDatas));
  }
);

// 监听对账单ID是否发生变化
const watchBillNo = watch(
  () => billNo.value,
  newId => {
    getDataSource(newId);
  }
);

// 销毁监听
onUnmounted(() => {
  watchBillNo();
  updataDatas();
});

onMounted(() => {
  getDataSource(billNo.value);
});
</script>

<style scoped>
:deep(.n-input.n-input--disabled .n-input__input-el, .n-base-selection.n-base-selection--disabled) {
  color: var(--n-text-color);
}
.n-form-item {
  height: 22px;
}
:deep(.n-form-item-label__text) {
  font-size: 12px;
}
.info-data {
  font-size: 12px;
  line-height: 100%;
  position: absolute;
  display: flex;
  align-items: center;
  width: calc(100% - 560px);
  height: 45px;
  left: 15px;
  bottom: 0;
  z-index: 1;
}

.info-data li {
  float: left;
  vertical-align: middle;
  margin-right: 15px;
}

.info-data li span {
  display: inline-block;
  white-space: nowrap;
}

.info-data li span:first-child {
  margin-right: 5px;
}
</style>
